package com.yz.rabbitmqspringboot.producer;

import com.yz.rabbitmqspringboot.pojo.Order;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RabbitSender implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(Object msg, Map<String,Object> properties){
        MessageHeaders mhs = new MessageHeaders(properties);
        Message message = MessageBuilder.createMessage(msg, mhs);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        rabbitTemplate.convertAndSend("springboot-fanout-exchange","",message,new CorrelationData("im is CorrelationData"));
    }

    public void send(String exchangeName,String routingKey,Object msg, Map<String,Object> properties){
        MessageHeaders mhs = new MessageHeaders(properties);
        Message message = MessageBuilder.createMessage(msg, mhs);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        rabbitTemplate.convertAndSend(exchangeName,routingKey,message,new CorrelationData("im is CorrelationData"));
    }

    public void sendOrder(String exchangeName, String routingKey, Order order){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        rabbitTemplate.convertAndSend(exchangeName,routingKey,order,new CorrelationData("im is CorrelationData"));
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        System.err.println("correlationData: "+correlationData);
        System.err.println("ack: "+ack);
        if(!ack){
            System.err.println("cause: "+cause);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returned) {
        System.err.println(returned);
    }
}
